#include "blockqueue.hpp"
#include "task.hpp"
#include <iostream>
#include <unistd.h>
#include <time.h>
#include <cstdlib>
#include <cstdio>
#include <string>

// 消费者
void *Consumer(void *args)
{
    //pthread_detach(pthread_self()); // 线程分离
    BlockQueue<Task> *bq = static_cast<BlockQueue<Task> *>(args);
    while (true)
    {
        Task task = bq->Pop();
        //运算
        task.run();
        cout << task.GetRet() << pthread_self() << endl;
        //std::cout << "Consumer use  " << bq->Pop() << std::endl;
        sleep(1);
    }
}

// 生产者
void *Productor(void *args)
{
    //pthread_detach(pthread_self()); // 线程分离
    BlockQueue<Task> *bq = static_cast<BlockQueue<Task> *>(args);
    while (true)
    {
        int data1 = rand() % 10 + 1;
        int len = opers.size();
        char oper = opers[rand()%len];
        int data2 = rand() % 5;

        Task task(data1, data2, oper);
        bq->Push(task);
        std::cout << "Productor create  " << data1 << oper << data2 << "= ?" << pthread_self() << std::endl;
        sleep(1);
    }
}

int main()
{
    srand(time(0));
    BlockQueue<Task> *bq = new BlockQueue<Task>();
    pthread_t c[3], p[5];
    // 创建两个线程
    for(int i = 0;i<3;i++)
    {
        pthread_create(c + i, nullptr, Consumer, bq);
    }
    for(int i = 0;i<5;i++)
    {
        pthread_create(p + i, nullptr, Productor, bq);
    }

    for(int i = 0;i<3;i++)
    {
        pthread_join(c[i], nullptr);
    }
    for(int i = 0;i<5;i++)
    {
        pthread_join(p[i], nullptr);
    }

    delete bq;
    return 0;
}